import logging

import pymysql


# 封装数据库操作类
class DButil():
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn == None:
            cls.conn = pymysql.connect(
                host="211.103.136.244",
                port=7061,
                user="student",
                password="iHRM_student_2021",
                database="ihrm",
                charset="utf8"
            )
            logging.info("数据库连接成功")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn != None:
            cls.conn.close()
            cls.conn = None

    # 常用方法 查询
    @classmethod
    def select_one(cls, sql):
        cursor = None
        res = None
        try:
            # 建立连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)

            # 提取一条结果
            res = cursor.fetchone()

        except Exception as err:
            print("错误:", err)
        finally:
            # 关闭游标
            cursor.close()
            #  关闭连接
            cls.__close_conn()

            # 返回sql结果
            return res

    # 常用 增删改
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        res = None
        try:
            # 建立连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # print("受影响的行数:", cls.conn.affected_rows())
            logging.info("受影响的行数:", cls.conn.affected_rows())
            # 提交事务
            cls.conn.commit()

        except Exception as err:
            print("错误:", str(err))
            # 回滚事务
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            #  关闭连接
            cls.__close_conn()
